#include "comet.h"

Comet::Comet()
{
	position = Vector2(-1000, -1000);
	timeUnSpawned = 0;
	timeElapsed = 0;
	randomSpawn = 0.001;
	speed = 0.3f;

	SetupImages();

	screenWidth = Iw2DGetSurfaceWidth();
	screenHeight = Iw2DGetSurfaceHeight();

	screenBox = BoundingBox(Vector2(screenWidth / 2, screenHeight / 2), screenWidth, screenHeight);

	boundingBox = BoundingBox(position, width, height);
}

Comet::~Comet()
{
	CleanupImages();
}

void Comet::SetupImages()
{
	cometSprite = Iw2DCreateImageResource("comet");
	width  = cometSprite->GetWidth();
    height = cometSprite->GetHeight();
	widthHalf = width / 2;
	heightHalf = height / 2;
}

void Comet::CleanupImages()
{
	if(cometSprite != NULL)
	{
		delete cometSprite;
		cometSprite = NULL;
	}
}

void Comet::Render()
{
	Iw2DDrawImage(cometSprite, CIwSVec2((int16)position.x - widthHalf, (int16)position.y - heightHalf));
}

void Comet::Update(int deltaTimeMs)
{
	timeElapsed += deltaTimeMs;

	if(timeElapsed >= 5000)
	{
		if(randomSpawn < 0.8)
		{
			randomSpawn = randomSpawn * 1.2;
		}
		timeElapsed = 0;
	}

	if(boundingBox.Intersects(screenBox))
	{
		//This is what moves the ufo each frame
		position += direction * (float)(deltaTimeMs * speed);
	}
	else
	{
		timeUnSpawned += deltaTimeMs;
	}

	if(timeUnSpawned > 0)
	{
		float random = Random::Instance()->RandomFloatZeroToOne();
		if(randomSpawn >= random)
		{
			Spawn();
		}
	}

	boundingBox.UpdatePosition(position);
}

void Comet::Spawn()
{
	timeUnSpawned = 0;

	int random = Random::Instance()->RandomIntBetween(1,8);
	
	//Top left to right
	if(random == 1)
	{
		direction = Vector2(1,0);
		position = Vector2(-widthHalf + 1, PLANET_RADIUS * 2);
	}
	//Bottom left to right
	else if(random == 2)
	{
		direction = Vector2(1,0);
		position = Vector2(-widthHalf + 1, screenHeight- PLANET_RADIUS * 2);
	}
	//Top right to left
	else if(random == 3)
	{
		direction = Vector2(-1,0);
		position = Vector2(screenWidth + widthHalf - 1, PLANET_RADIUS * 2);
	}
	//Bottom right to left
	else if(random == 4)
	{
		direction = Vector2(-1,0);
		position = Vector2(screenWidth + widthHalf - 1, screenHeight - PLANET_RADIUS * 2);
	}
	//Left top to bottom
	else if(random == 5)
	{
		direction = Vector2(0,1);
		position = Vector2(PLANET_RADIUS * 2, -heightHalf + 1);
	}
	//Right top to bottom
	else if(random == 6)
	{
		direction = Vector2(0,1);
		position = Vector2(screenWidth - PLANET_RADIUS * 2, -heightHalf + 1);
	}
	//Left bottom to top
	else if(random == 7)
	{
		direction = Vector2(0,-1);
		position = Vector2(PLANET_RADIUS * 2, screenHeight + heightHalf - 1);
	}
	//Right bottom to top
	else if(random == 8)
	{
		direction = Vector2(0,-1);
		position = Vector2(screenWidth - PLANET_RADIUS * 2, screenHeight + heightHalf - 1);
	}
}